package com.cloud.eurekaserver.controller;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;


/**
 * 演示eureka中本地缓存的使用
 * 这是使用的Google的 guava 缓存框架
 */
@RestController
public class LocalCacheController {

    LoadingCache<String,String> localCache = CacheBuilder
            .newBuilder()
            .expireAfterWrite(5, TimeUnit.SECONDS)
            .build(new CacheLoader<String, String>() {
        @Override
        public String load(String key) throws Exception {
            //如果本地缓存中没有这个key，则在这里调用方法去获取，并添加到缓存
            return "load：" + new Random().nextInt(100);
        }
    });

    @RequestMapping("/cache-get/{id}")
    public String loadCache(@PathVariable("id")String id){
        try {
            return localCache.get(id);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/cache-set/{id}")
    public String setCache(@PathVariable("id")String id){
       localCache.put(id,"set：" + new Random().nextInt(100));
       return "success";
    }

}
